import type { AppRouteRecordRaw, AppRouteModule } from '@/router/types';

import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes/basic';
import { useAppStore } from '@/store/modules/app';
import { mainOutRoutes } from './mainOut';
import { PageEnum } from '@/enums/pageEnum';
import { t } from '@/hooks/web/useI18n';
import { getToken } from '@/utils/cookie';
import { getMyMenu } from '@/api/escloud/menu';
// import.meta.glob() 直接引入所有的模块 Vite 独有的功能
const modules = import.meta.glob('./modules/**/*.ts', { eager: true });
const routeModuleList: AppRouteModule[] = [];

// 加入到路由集合中
Object.keys(modules).forEach((key) => {
  const mod = (modules as Recordable)[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

export const asyncRoutes = [PAGE_NOT_FOUND_ROUTE, ...routeModuleList];

// 根路由
export const RootRoute: AppRouteRecordRaw = {
  path: '/',
  name: 'Root',
  redirect: PageEnum.BASE_HOME,
  meta: {
    title: 'Root',
  },
};

// export const LoginRoute: AppRouteRecordRaw = {
//   path: '/login',
//   name: 'Login',
//   component: () => import('@/views/sys/login/Login.vue'),
//   meta: {
//     title: t('routes.basic.login'),
//   },
// };
export const outboundRoute: AppRouteRecordRaw = {
  path: '/h5/outbound',
  name: 'Outbound',
  component: () => import('@/views/h5/outbound.vue'),
  meta: {
    title: t('routes.basic.login'),
  },
};
export const signRoute: AppRouteRecordRaw = {
  path: '/h5/sign',
  name: 'Sign',
  component: () => import('@/views/h5/sign.vue'),
  meta: {
    title: t('routes.basic.login'),
  },
};

// Basic routing without permission
// 未经许可的基本路由
export const basicRoutes = [
  // LoginRoute,
  outboundRoute,
  signRoute,
  RootRoute,
  ...mainOutRoutes,
  REDIRECT_ROUTE,
  PAGE_NOT_FOUND_ROUTE,
];
/* eslint-disable */
// const SYS_TYPE = 'Platform';

export async function fetchAndProcessMenu() {
  return new Promise(async (r, j) => {
    let initRouteList: Array<{ name: string; children: any[] }> = [];
    let routeList: Array<{ name: string; children: any[] }> = [];
    let sysList: Array<{ name: string; text: string }> = [];
    let appStore = useAppStore();
    const SYS_TYPE = appStore.getSystem;
    // const SYS_TYPE = '';
    console.log('看看当前的系统：', SYS_TYPE);
    if (getToken()) {
      try {
        const res = await getMyMenu(); // 使用 await 等待 Promise 解决
        // console.log('我的菜单结果：', res.data);
        let sysFlag = true;
        res.forEach((element) => {
          if (element.children.length) {
            // console.log('name', element.name, element.description);
            sysList.push({
              name: element.name,
              text: element.description,
            });
          }
          if (SYS_TYPE && element.name === SYS_TYPE) {
            initRouteList = [element];
            // console.log('[element]', element);
          } else if (!SYS_TYPE && sysFlag) {
            if (element.children.length) {
              console.log('elementchildren', element);
              initRouteList = [element];
              sysFlag = false;
            }
          }
        });
      } catch (error) {
        j(error);
        // 处理错误
        console.error('获取菜单时出错:', error);
      }
      routeList = updateRouteConfig(initRouteList);
      appStore.setSysList(sysList);
      console.log('看看当前有哪些路由：', sysList);
      // 在这里或之后执行需要等待菜单加载完毕的代码
      // ...
    }
    if (routeList.length) {
      r(routeList[0].children || []);
    } else {
      r([]);
    }
  });
}
let permissionList = [];
function updateRouteConfig(routes: RouteConfig[]): RouteConfig[] {
  return routes.map((route) => {
    // 复制当前路由对象以避免直接修改原始对象
    const updatedRoute: RouteConfig = { ...route };

    let appStore = useAppStore();
    // 添加权限，用于区分路由展示哪一端
    updatedRoute['meta'] = {};
    // updatedRoute.meta['roles'] = [RoleEnum[updatedRoute.name.toUpperCase()]];
    updatedRoute['path'] = updatedRoute.href;
    updatedRoute.meta['title'] = updatedRoute.description;
    // updatedRoute['type'] = updatedRoute.name;
    // 活了
    if (updatedRoute.type == 'HIDDEN') {
      updatedRoute.meta['hideChildrenInMenu'] = true;
    }
    if (updatedRoute.type == 'HIDEMENU') {
      updatedRoute.meta['hideMenu'] = true;
    }
    if (updatedRoute.type == 'BUTTON') {
      updatedRoute.meta['hideMenu'] = true;
      permissionList.push(updatedRoute['path']);
      appStore.setPermissionList(permissionList);
    }
    // 重定义路由名字
    updatedRoute['name'] = updatedRoute.description;
    // // 如果component是字符串'Layout'，则替换为实际的Layout组件
    // if (updatedRoute.component === 'Layout') {
    //   updatedRoute.component = LAYOUT; // 假设Layout是一个已经导入的React组件
    // }
    // 更新component为动态导入，如果它是字符串并且看起来像一个文件路径
    // if (typeof updatedRoute.component === 'string' && updatedRoute.component.includes('/')) {
    //   // 假设'@/views'是项目中的绝对路径别名，指向src/views目录
    //   const viewPath = updatedRoute.component.replace(/^\//, ''); // 移除开头的斜杠（如果有的话）
    //   updatedRoute.component = () => import(`/@/views/${viewPath}.vue`);
    // }
    // 如果存在children，递归处理
    if (updatedRoute.children) {
      updatedRoute.children = updateRouteConfig(updatedRoute.children);
    }

    return updatedRoute;
  });
}
/* eslint-enable */
